import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { RequestStatusCode, RequestStatusMessage } from 'src/constants';
import { ReturnResult } from 'src/base/return-result';
import { YixianTongFields } from 'src/entities/yixiantong-fields';
import { YixiantongService } from 'src/yixiantong/yixiantong.service';
import { YixiantongCitiesDto } from './yixiantong-cities.dto';

@Injectable()
export class YixiantongCitiesService {
  constructor(
    private readonly yixiantongService: YixiantongService,
    @InjectRepository(YixianTongFields)
    private readonly yixianTongFieldsRepository: Repository<YixianTongFields>,
  ) {}

  async getList(
    page: number,
    pageSize: number,
    keyword: string
  ) {
    try {
      let queryBuilder = this.yixianTongFieldsRepository.createQueryBuilder('city')
        .skip((page - 1) * pageSize)
        .take(pageSize)
        .where(`city.status = 1`);

      if (keyword?.length) {
        queryBuilder = queryBuilder.andWhere(`
        city.name like '%${keyword}%'
          or city.aliasName like '%${keyword}%'
          or city.description like '%${keyword}%'
        `
        );
      }

      const list = await queryBuilder
        .select(['city.id', 'city.name', /* 'city.img', */ 'city.aliasName', 'city.description', 'city.createTime', 'city.updateTime'])
        .orderBy('city.updateTime', 'DESC')
        .getMany();

      const total = (await this.yixianTongFieldsRepository.findBy({ status: 1 })).length;
      return new ReturnResult(
        RequestStatusCode.Success,
        RequestStatusMessage.GetListSuccess,
        { list, total },
      );
    } catch (e) {
      return new ReturnResult(
        RequestStatusCode.NotFound,
        RequestStatusMessage.GetListError,
        null,
        'Fail'
      );
    }
  }

  async getCityDetail(id: number) {
    const detail = await this.yixianTongFieldsRepository.findOneBy({ id });
    if (!detail) {
      return new ReturnResult(
        RequestStatusCode.NotFound,
        RequestStatusMessage.GetDetailError,
        null,
        'Fail'
      );
    }
    return new ReturnResult(
      RequestStatusCode.Success,
      RequestStatusMessage.GetDetailSuccess,
      detail
    );
  }

  async createCity(formData: YixiantongCitiesDto) {
    try {
      if (!formData.description) {
        formData.description = '';
      }
      const result = await this.yixianTongFieldsRepository.save(formData);
      return new ReturnResult(
        RequestStatusCode.Success,
        RequestStatusMessage.CreateSuccess,
        result
      );
    } catch (e) {
      return new ReturnResult(
        RequestStatusCode.OperateError,
        `${RequestStatusMessage.CreateError}：${e instanceof Error ? e.message : 'Error'}`,
        null,
        'Fail'
      );
    }
  }

  async updateCity(id: number, newFormData: YixiantongCitiesDto) {
    try {
      const formData = await this.yixianTongFieldsRepository.findOneBy({ id });
      if (!formData) {
        return new ReturnResult(1, '更新失败：未找到数据！', null, 'Fail');
      }
      // 更新数据
      formData.name = newFormData.name;
      formData.aliasName = newFormData.aliasName;
      formData.description = newFormData.description;
      formData.img = newFormData.img;
      formData.updateTime = new Date();
      await this.yixianTongFieldsRepository.save(formData);
      return new ReturnResult(0, '更新成功！', {});
    } catch (e) {
      return new ReturnResult(1, `更新失败：${e instanceof Error ? e.message : 'Error'}`, null, 'Fail');
    }
  }

  async deleteCity(id: number) {
    try {
      // 硬删除
      // await this.yixianTongFieldsRepository.delete(id);

      // 软删除
      const formData = await this.yixianTongFieldsRepository.findOneBy({ id });
      if (!formData) {
        return new ReturnResult(
          RequestStatusCode.NotFound,
          `${RequestStatusMessage.DeleteError}：${RequestStatusMessage.NotFound}`,
          null,
          'Fail'
        );
      }
      formData.status = 0;
      await this.yixianTongFieldsRepository.save(formData);
      return new ReturnResult(
        RequestStatusCode.Success,
        RequestStatusMessage.DeleteSuccess,
        {}
      );
    } catch (e) {
      return new ReturnResult(
        RequestStatusCode.OperateError,
        `${RequestStatusMessage.DeleteError}：${e instanceof Error ? e.message : 'Error'}`,
        null,
        'Fail'
      );
    }
  }
}
